﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Model.CSP;
using CSP.Bll.IObjectBlls;
using CSP.Bll;
using CSP.Common.Tools;
using System.Collections.ObjectModel;
using CSP.Web.Master;
using CSP.Web.UserControls;

namespace CSP.Web.MyHome.ContactWay
{
    public partial class Info : CSPMyHome
    {


        private CSPBllFactory _factory;

        private IContactWayBll _contactWayBll;

        protected void Page_Load(object sender, EventArgs e)
        {
            //指定被选中的导航
            ((HomeMaster)Master).SelectedNavigationLink = MyHomeLeftNavigationLink.ContactWay;

            if (!IsPostBack)
            {

                if (Request["modifyid"] != null)
                {
                    LB_Title.Text = "修改联系方式";
                    LoadModifyContactWayUI(Convert.ToInt32(Request.QueryString["modifyid"]));
                }
                else if (Request["deleteid"] != null)
                {
                    Response.ClearContent();
                    Response.ContentType = "text/plain";
                    Response.Write(RemoveContactWayBll(Convert.ToInt32(Request["deleteid"])));
                    Response.End();
                    return;
                }
                InitInfo();
                BindContactWayUI();
            }
        }


        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (Request["modifyid"] != null)
            {
                //更新修改
                UpdateContactWay(Convert.ToInt32(Request.QueryString["modifyid"]));
            }
            else
            {
                int contactWay=GetCountByUser();
                if (contactWay>=6)
                {
                    this.Alert("联系方式的数量不能超过6个");
                    return;
                }
                //添加
                CreateContactWay();
                
            }
        }

        private void InitInfo()
        {
            this.RD_QQ.Checked = true;
        }

        private void CreateContactWay()
        {
            Model.CSP.ContactWay contactWay = new Model.CSP.ContactWay
            {
                nickname = this.Txt_Name.Value,
                address = this.Txt_Address.Value,
                type = Convert.ToByte(RD_QQ.Checked ? 1 : 0),
                username = UserProvider.UserName,
                lastmodified = BitConverter.GetBytes(CommonTool.ConvertToTimeSpan(DateTime.Now))
            };

            _factory = CSPBllFactory.GetInstance();
            using (_contactWayBll = _factory.GetContactWayBll())
            {
                try
                {
                    _contactWayBll.Add(contactWay);

                }
                catch (Exception ex)
                {
                    LoggerProvider.Error(contactWay, ex);
                    this.FailRedirect("提交未失败", "/MyHome/ContactWay/Info.aspx");
                }
            }
            if(Request["urlback"]!=null){
                Response.Redirect(Request["urlback"].ToString());
            }
            this.SuccessfullRedirect("提交成功", "/MyHome/ContactWay/Info.aspx");
        }

        /// <summary>
        /// 绑定联系方式
        /// </summary>
        private void BindContactWayUI()
        {
            ICollection<Model.CSP.ContactWay> contactWays = GetContactWaysByUser();
            if (contactWays == null)
            {
                contactWays = new Collection<Model.CSP.ContactWay>();
            }
            this.R_ContactWay.DataSource = contactWays;
            this.R_ContactWay.DataBind();
        }

        private ICollection<Model.CSP.ContactWay> GetContactWaysByUser()
        {
            ICollection<Model.CSP.ContactWay> result = null;
            _factory = CSPBllFactory.GetInstance();
            using (_contactWayBll = _factory.GetContactWayBll())
            {
                result = _contactWayBll.FindByUser(UserProvider.UserName);
            }

            return result;
        }

        private void UpdateContactWay(int id)
        {
            _factory = CSPBllFactory.GetInstance();
            _contactWayBll = _factory.GetContactWayBll();

            Model.CSP.ContactWay contactWay = GetContactWayById(_contactWayBll, id);

            contactWay.nickname = this.Txt_Name.Value;
            contactWay.address = this.Txt_Address.Value;
            contactWay.type = Convert.ToByte(RD_QQ.Checked ? 1 : 0);
            contactWay.lastmodified = BitConverter.GetBytes(CommonTool.ConvertToTimeSpan(DateTime.Now));

            try
            {
                _contactWayBll.Update(contactWay);
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(contactWay, ex);
                this.FailRedirect("提交未失败", "/MyHome/ContactWay/Info.aspx");
            }

            this.SuccessfullRedirect("提交成功", "/MyHome/ContactWay/Info.aspx");
        }

        /// <summary>
        /// 加载生成UI
        /// </summary>
        /// <param name="id"></param>
        private void LoadModifyContactWayUI(int id)
        {
            _factory = CSPBllFactory.GetInstance();
            _contactWayBll = _factory.GetContactWayBll();

            Model.CSP.ContactWay contactWay = GetContactWayById(_contactWayBll, id);

            this.Txt_Name.Value = contactWay.nickname;
            this.Txt_Address.Value = contactWay.address;
            if (contactWay.type == 1)
            {
                RD_QQ.Checked = true;
            }
            else
            {
                RD_WangWang.Checked = true;
            }

        }

        private Model.CSP.ContactWay GetContactWayById(IContactWayBll contactWayBll, int id)
        {
            Model.CSP.ContactWay result = null;
            _factory = CSPBllFactory.GetInstance();
            result = contactWayBll.GetDataByIdAndUser(id, UserProvider.UserName);


            return result;
        }

        /// <summary>
        /// 根据用户名获取数量
        /// </summary>
        /// <returns></returns>
        private int GetCountByUser()
        {
            _factory = CSPBllFactory.GetInstance();
            int result = 0;
            using (_contactWayBll = _factory.GetContactWayBll())
            {
                result = _contactWayBll.GetCountByUser(UserProvider.UserName);
            }

            return result;
        }

        private string RemoveContactWayBll(int id)
        {
            _factory = CSPBllFactory.GetInstance();
            _contactWayBll = _factory.GetContactWayBll();

            try
            {
                var contactWay = _contactWayBll.DeleteByIdAndUser(id, UserProvider.UserName);
                if (contactWay == null)
                {
                    return "{\"status\":2,\"msg\":\"权限不足!\"}";
                }

                return "{\"status\":1,\"msg\":\"操作成功!\"}";
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(id, ex);
                return "{\"status\":0,\"msg\":\"操作失败!\"}";
            }
        }

        /// <summary>
        /// 获取联系方式链接字符串
        /// </summary>
        /// <param name="address">API 的地址</param>
        /// <param name="contactType">0旺旺,1QQ</param>
        /// <param name="urlType">0图片，1URL</param>
        /// <returns></returns>
        protected string GetContactURL(string address, int contactType, int urlType)
        {
            string result = "";
            if (contactType == 0 && urlType == 0)
            {
                result = CSP.Common.Tools.CommonTool.GetTaoBaoContactImgURL(address);
            }
            else if (contactType == 0 && urlType == 1)
            {
                result = CSP.Common.Tools.CommonTool.GetTaoBaoContactURL(address);
            }
            else if (contactType == 1 && urlType == 0)
            {
                result = CSP.Common.Tools.CommonTool.GetQQContactImgURL(address);
            }
            else if (contactType == 1 && urlType == 1)
            {
                result = CSP.Common.Tools.CommonTool.GetQQContactURL(address);
            }

            return result;
        }


    }
}